import React, { useState, useEffect } from 'react';
import { 
  Card, Button, Space, Radio, Checkbox, Input, message, 
  Progress, Tag, Affix, Modal, Spin 
} from 'antd';
import { 
  ClockCircleOutlined, SaveOutlined, SendOutlined, 
  ExclamationCircleOutlined, CheckCircleOutlined 
} from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { Paper, Submission, SubmitAnswer, QuestionType, PaperQuestion } from '@/types/question';
import { questionService } from '@/services/questionService';
import CodeHighlight from '@/components/CodeHighlight';
import styles from './PaperExam.module.css';

const { TextArea } = Input;

const PaperExam: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [paper, setPaper] = useState<Paper | null>(null);
  const [submission, setSubmission] = useState<Submission | null>(null);
  const [answers, setAnswers] = useState<Record<number, any>>({});
  const [timeSpent, setTimeSpent] = useState<Record<number, number>>({});
  const [startTimes, setStartTimes] = useState<Record<number, number>>({});
  const [remainingTime, setRemainingTime] = useState<number>(0);

  // 初始化
  useEffect(() => {
    if (id) {
      initExam();
    }
  }, [id]);

  // 计时器
  useEffect(() => {
    if (paper && paper.duration > 0 && remainingTime > 0) {
      const timer = setInterval(() => {
        setRemainingTime(prev => {
          if (prev <= 1) {
            handleSubmit();  // 时间到自动提交
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      return () => clearInterval(timer);
    }
  }, [paper, remainingTime]);

  const initExam = async () => {
    if (!id) return;
    setLoading(true);
    try {
      // 开始答题
      const response = await questionService.startPaper(Number(id));
      const submissionData = response.data.data;
      setSubmission(submissionData);
      setPaper(submissionData.paper_detail as any);

      // 设置倒计时
      if (submissionData.paper_detail && submissionData.paper_detail.duration > 0) {
        setRemainingTime(submissionData.paper_detail.duration * 60);
      }

      // 加载已保存的答案
      if (submissionData.answer_records) {
        const savedAnswers: Record<number, any> = {};
        submissionData.answer_records.forEach((record: any) => {
          savedAnswers[record.question] = record.user_answer;
        });
        setAnswers(savedAnswers);
      }
    } catch (error: any) {
      message.error(error.response?.data?.message || '初始化失败');
      navigate('/client/paper/list');
    } finally {
      setLoading(false);
    }
  };

  // 更新答案
  const updateAnswer = (questionId: number, answer: any) => {
    setAnswers({
      ...answers,
      [questionId]: answer,
    });

    // 记录开始答题时间
    if (!startTimes[questionId]) {
      setStartTimes({
        ...startTimes,
        [questionId]: Date.now(),
      });
    }
  };

  // 保存答案
  const handleSaveAnswer = async (questionId: number) => {
    if (!id) return;
    try {
      const spent = startTimes[questionId] 
        ? Math.floor((Date.now() - startTimes[questionId]) / 1000)
        : 0;
      
      await questionService.saveAnswer(Number(id), {
        question_id: questionId,
        answer: answers[questionId],
        time_spent: spent,
      });
      message.success('答案已保存');
    } catch (error) {
      message.error('保存失败');
    }
  };

  // 提交试卷
  const handleSubmit = () => {
    Modal.confirm({
      title: '确认提交',
      icon: <ExclamationCircleOutlined />,
      content: '提交后将无法修改，确定要提交试卷吗？',
      okText: '确定提交',
      cancelText: '取消',
      onOk: async () => {
        if (!id || !paper) return;
        
        setSubmitting(true);
        try {
          const submitData: SubmitAnswer[] = [];
          
          paper.paper_questions?.forEach((pq) => {
            const questionId = pq.question;
            const spent = startTimes[questionId] 
              ? Math.floor((Date.now() - startTimes[questionId]) / 1000)
              : 0;
            
            submitData.push({
              question_id: questionId,
              answer: answers[questionId] || null,
              time_spent: spent,
            });
          });

          const response = await questionService.submitPaper(Number(id), {
            answers: submitData,
          });

          message.success(response.data.message || '提交成功');
          navigate(`/client/paper/result/${response.data.data.id}`);
        } catch (error: any) {
          message.error(error.response?.data?.message || '提交失败');
        } finally {
          setSubmitting(false);
        }
      },
    });
  };

  // 渲染题目
  const renderQuestion = (pq: PaperQuestion, index: number) => {
    const question = pq.question_detail;
    if (!question) return null;

    const questionId = pq.question;
    const currentAnswer = answers[questionId];

    return (
      <Card
        key={questionId}
        className={styles.questionCard}
        title={
          <Space>
            <span>{index + 1}.</span>
            <Tag color="cyan">{question.type_display}</Tag>
            <span>{question.title || question.content.substring(0, 50)}</span>
            <Tag color="orange">{pq.score}分</Tag>
          </Space>
        }
        extra={
          <Button 
            size="small" 
            onClick={() => handleSaveAnswer(questionId)}
          >
            保存
          </Button>
        }
      >
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          {/* 题目内容 */}
          <div className={styles.questionContent}>
            {question.content}
          </div>

          {/* 代码块 */}
          {question.has_code && question.code_content && (
            <CodeHighlight
              code={question.code_content}
              language={question.code_language || 'cpp'}
            />
          )}

          {/* 答题区域 */}
          {renderAnswerArea(question, questionId, currentAnswer)}

          {/* 提示 */}
          {question.hint && (
            <div className={styles.hint}>
              💡 提示：{question.hint}
            </div>
          )}
        </Space>
      </Card>
    );
  };

  // 渲染子题答题区域（用于综合题）
  const renderSubQuestionArea = (
    subQuestion: any, 
    subQuestionId: number, 
    subAnswer: any,
    updateSubAnswer: (id: number, answer: any) => void
  ) => {
    switch (subQuestion.type) {
      case QuestionType.SINGLE_CHOICE:
      case QuestionType.TRUE_FALSE:
        return (
          <Radio.Group
            value={subAnswer}
            onChange={(e) => updateSubAnswer(subQuestionId, e.target.value)}
          >
            <Space direction="vertical">
              {subQuestion.choices?.map((choice: any) => (
                <Radio key={choice.key} value={choice.key}>
                  <span>{choice.key}. {choice.content}</span>
                </Radio>
              ))}
            </Space>
          </Radio.Group>
        );

      case QuestionType.MULTIPLE_CHOICE:
        return (
          <Checkbox.Group
            value={subAnswer || []}
            onChange={(values) => updateSubAnswer(subQuestionId, values)}
          >
            <Space direction="vertical">
              {subQuestion.choices?.map((choice: any) => (
                <Checkbox key={choice.key} value={choice.key}>
                  <span>{choice.key}. {choice.content}</span>
                </Checkbox>
              ))}
            </Space>
          </Checkbox.Group>
        );

      case QuestionType.FILL_BLANK:
        return (
          <Input
            value={subAnswer || ''}
            onChange={(e) => updateSubAnswer(subQuestionId, e.target.value)}
            placeholder="请输入答案"
            style={{ width: 300 }}
          />
        );

      default:
        return null;
    }
  };

  // 渲染答题区域
  const renderAnswerArea = (question: any, questionId: number, currentAnswer: any) => {
    switch (question.type) {
      case QuestionType.SINGLE_CHOICE:
      case QuestionType.TRUE_FALSE:
        return (
          <Radio.Group
            value={currentAnswer}
            onChange={(e) => updateAnswer(questionId, e.target.value)}
          >
            <Space direction="vertical">
              {question.choices?.map((choice: any) => (
                <Radio key={choice.key} value={choice.key}>
                  <span>{choice.key}. {choice.content}</span>
                  {choice.has_code && choice.code && (
                    <CodeHighlight 
                      code={choice.code} 
                      language={choice.language || 'cpp'}
                    />
                  )}
                </Radio>
              ))}
            </Space>
          </Radio.Group>
        );

      case QuestionType.MULTIPLE_CHOICE:
        return (
          <Checkbox.Group
            value={currentAnswer || []}
            onChange={(values) => updateAnswer(questionId, values)}
          >
            <Space direction="vertical">
              {question.choices?.map((choice: any) => (
                <Checkbox key={choice.key} value={choice.key}>
                  <span>{choice.key}. {choice.content}</span>
                  {choice.has_code && choice.code && (
                    <CodeHighlight 
                      code={choice.code} 
                      language={choice.language || 'cpp'}
                    />
                  )}
                </Checkbox>
              ))}
            </Space>
          </Checkbox.Group>
        );

      case QuestionType.FILL_BLANK:
        return (
          <Space direction="vertical" style={{ width: '100%' }}>
            {Array.from({ length: question.blank_count || 1 }).map((_, idx) => (
              <div key={idx}>
                <span>第{idx + 1}空：</span>
                <Input
                  value={currentAnswer?.[idx] || ''}
                  onChange={(e) => {
                    const newAnswers = [...(currentAnswer || [])];
                    newAnswers[idx] = e.target.value;
                    updateAnswer(questionId, newAnswers);
                  }}
                  placeholder={`请输入第${idx + 1}空的答案`}
                  style={{ width: 300 }}
                />
              </div>
            ))}
          </Space>
        );

      case QuestionType.COMPOSITE:
        // 综合题的答案是一个对象，key为子题ID
        const compositeAnswer = currentAnswer || {};
        
        // 更新子题答案的特殊处理函数
        const updateSubAnswer = (subQuestionId: number, subAnswer: any) => {
          const newCompositeAnswer = {
            ...compositeAnswer,
            [subQuestionId]: subAnswer,
          };
          updateAnswer(questionId, newCompositeAnswer);
        };
        
        return (
          <div>
            <div style={{ marginBottom: 16, fontWeight: 'bold' }}>请回答以下问题：</div>
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              {question.sub_questions?.map((subQ: any, subIdx: number) => (
                <Card key={subQ.id} size="small" title={`(${subIdx + 1}) ${subQ.content}`}>
                  {renderSubQuestionArea(subQ, subQ.id, compositeAnswer[subQ.id], updateSubAnswer)}
                </Card>
              ))}
            </Space>
          </div>
        );

      default:
        return null;
    }
  };

  // 计算答题进度
  const answeredCount = Object.keys(answers).length;
  const totalCount = paper?.paper_questions?.length || 0;
  const progress = totalCount > 0 ? (answeredCount / totalCount) * 100 : 0;

  if (loading) {
    return <Spin tip="加载中..." size="large" style={{ marginTop: '20%' }} />;
  }

  return (
    <div className={styles.container}>
      {/* 顶部信息栏 */}
      <Affix offsetTop={0}>
        <Card className={styles.headerCard}>
          <Space style={{ width: '100%', justifyContent: 'space-between' }}>
            <Space size="large">
              <h2>{paper?.title}</h2>
              {paper?.duration && paper.duration > 0 && (
                <Tag icon={<ClockCircleOutlined />} color="red" style={{ fontSize: 16 }}>
                  剩余：{Math.floor(remainingTime / 60)}:{String(remainingTime % 60).padStart(2, '0')}
                </Tag>
              )}
            </Space>
            
            <Space>
              <span>进度：{answeredCount}/{totalCount}</span>
              <Progress 
                type="circle" 
                percent={Math.floor(progress)} 
                width={50} 
                strokeColor={progress === 100 ? '#52c41a' : '#1890ff'}
              />
              <Button 
                type="primary" 
                icon={<SendOutlined />}
                onClick={handleSubmit}
                loading={submitting}
                danger
              >
                提交试卷
              </Button>
            </Space>
          </Space>
        </Card>
      </Affix>

      {/* 题目列表 */}
      <div className={styles.questionsContainer}>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          {paper?.paper_questions?.map((pq, index) => renderQuestion(pq, index))}
        </Space>
      </div>
    </div>
  );
};

export default PaperExam;

